<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>2462. 雇佣 K 位工人的总代价</title>
</head>

<body>
	https://leetcode.cn/problems/total-cost-to-hire-k-workers/description/?envType=daily-question&envId=2024-05-01
</body>

<script>
	/**
	 * @param {number[]} costs
	 * @param {number} k
	 * @param {number} candidates
	 * @return {number}
	 */
	var totalCost = function (costs, k, candidates) {

		let total = 0;

		let indexArr = []
		let findIndex = null;
		for (i = 0; i < k; i++) {
			if (costs.length === 0) return total;

			let findVal = 0

			debugger
			if (costs.length > candidates * 2) {
				let startList = costs.slice(0, candidates);
				let endList = costs.slice(costs.length - candidates, costs.length);

				// let startMin = Math.min(...startList);
				// let endMine = Math.min(...endList);

				// if (startMin <= endMine) {
				// 	findIndex = costs.indexOf(startMin)
				// } else {
				// 	findIndex = endList.indexOf(endMine) + costs.length - candidates;
				// }

				let tempList = [...startList, ...endList];
				findVal = Math.min(...tempList);
				let mineIndex = tempList.indexOf(findVal);
				if (mineIndex > (candidates - 1)) {
					findIndex = mineIndex + costs.length - (2 * candidates);
				} else {
					findIndex = mineIndex
				}

				costs.splice(findIndex, 1)

			} else {
				findIndex = costs.indexOf(Math.min(...costs));
				findVal = costs.splice(findIndex, 1)[0];
			}

			indexArr.push(findIndex)
			total += findVal;
		}

		console.log(`[indexArr]`, indexArr)

		return total;
	};


	// let res = totalCost([17, 12, 10, 2, 7, 2, 11, 20, 8], 3, 4);
	// let res = totalCost([2, 2, 2, 2, 1, 2, 2, 2, 2], 9, 2);
	let res = totalCost([31, 25, 72, 79, 74, 65, 84, 91, 18, 59, 27, 9, 81, 33, 17, 58], 11, 2);
	console.log(res)
</script>

</html>